package Match

import (
	"sanguo/cluster"
	codecs "sanguo/codec/cs"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	ss_msg "sanguo/protocol/ss/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionMatch struct {
	transaction.TransactionBase
	user      *user.User
	req       *codecs.Message
	node_team cluster.PeerID
}

func (this *transactionMatch) GetModuleName() string {
	return "Match"
}

func (this *transactionMatch) GetReplyMsg() proto.Message {
	return nil
}

func (this *transactionMatch) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionMatch) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionMatch) Begin() {

	node_team, err := cluster.Random("team")
	if nil != err {
		node_game.Debugln("CreateTeam fail : no team server")
		this.user.EndTrans(this)
		return
	}
	msg := this.req.GetData().(*cs_message.MatchToS)
	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()
	if nil == role || !role.IsRoleModleData() {
		node_game.Debugln(role.GetUserID(), "fail no selected role")
		this.user.EndTrans(this)
		return
	}

	//匹配申请
	if msg.GetMsgType() == cs_message.MatchType_Request {

		arg := &ss_msg.Match{
			MsgType:         proto.Int32(1),
			BattleLevelType: proto.Int32(1),
			UserID:          proto.String(role.GetUserID()),
			RoleID:          proto.Uint64(role.GetID()),
			Game:            proto.String(node_game.GetSelfService().ToPeerID().ToString()),
		}

		_team := role.Team
		if _team != nil && _team.TeamHeader {
			arg.TeamID = proto.Uint64(_team.TeamID)
			cluster.PostMessage(node_team, arg)
		} else if _team == nil {
			cluster.PostMessage(node_team, arg)
		}

	} else if msg.GetMsgType() == cs_message.MatchType_Cancel { //匹配取消

		arg := &ss_msg.Match{
			MsgType: proto.Int32(2),
			UserID:  proto.String(role.GetUserID()),
			RoleID:  proto.Uint64(role.GetID()),
			Game:    proto.String(node_game.GetSelfService().ToPeerID().ToString()),
		}

		_team := role.Team
		if _team != nil {
			arg.TeamID = proto.Uint64(_team.TeamID)
			cluster.PostMessage(node_team, arg)
		} else {
			cluster.PostMessage(node_team, arg)
		}
	}

	this.user.EndTrans(this)

}

func (this *transactionMatch) End() {
}

func (this *transactionMatch) Timeout() {
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.MatchToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionMatch{
			user: user,
			req:  msg,
		}
	})
}
